// pages/goods_detail/goods_detail.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    detailData: [],
    swiperPreview: []
  },
  goods_id: "",
  getGoodsDetail: async function () {
    let { data } = await wx.goodsApi.getGoodsDetail({ goods_id: this.goods_id })
    console.log(data)
    let arr = []
    data.message.pics.forEach(item => {
      arr.push(item.pics_sma_url)
    })
    this.setData({
      detailData: data.message,
      swiperPreview: arr
    })
  },
  imgclick: function (e) {
    wx.previewImage({
      current: e.currentTarget.dataset.src,
      urls: this.data.swiperPreview
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.goods_id = options.goods_id
    this.getGoodsDetail()
  },
  handleCartAdd() {
    let cart = wx.getStorageSync('cart') || [];
    console.log("购物车数据", cart)
    let index = cart.findIndex(item => item.goods_id === this.data.detailData.goods_id)
    if (index === -1) {
      this.data.detailData.num = 1;
      cart.push(this.data.detailData);
    } else {
      cart[index].num++;
    }
    wx.setStorageSync('cart', cart);
    wx.showToast({
      title: '加入购物车成功',
      icon: 'success',
      mask: true
    })
  },
  handleCollect() {
    let collect = wx.getStorageSync('collect') || [];
    console.log(this.data.detailData.goods_id)
    let index = collect.findIndex(item => item.goods_id === this.data.detailData.goods_id)
    if (index === -1) {
      this.data.detailData.is_promote = true
      this.setData({
        detailData:this.data.detailData
      })
      collect.push(this.data.detailData);
      wx.setStorageSync('collect', collect);
      wx.showToast({
        title: '添加收藏成功',
        icon: 'success',
        mask: true
      })
    }else{
      this.data.detailData.is_promote = false
      this.setData({
        detailData:this.data.detailData
      })
      collect.splice(index,1);
      wx.setStorageSync('collect', collect);
      wx.showToast({
        title: '删除收藏成功',
        icon: 'error',
        mask: true
      })
    }

  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let pages = getCurrentPages();
    console.log(pages)
    let currentPage = pages[pages.length-1];
    console.log(currentPage)
    let op = currentPage.options;
    console.log("opaction===>onShow",op)
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})